export default class TypeWriterEffect extends Laya.Script {
    private charsPerSecond: number = 0.05*1000;//打字时间间隔
    private words: string;//保存需要显示的文字

    private isActive: boolean = false;
    private timer: number;//计时器
    private myText: fairygui.GLabel;
    private currentPos: number = 0;//当前打字位置
    private latTime: number;
    // Use this for initialization

    public SetData(gLabel: fairygui.GLabel) {
        this.myText = gLabel;
        this.latTime = Laya.timer.currTimer;
    }

    // Update is called once per frame
    onUpdate() {
        this.OnStartWriter();
    }

    public StartType(strMessage: string) {
        this.timer = 0;
        this.currentPos = 0;
        this.words = strMessage;
        this.myText.text = "";//获取Text的文本信息，保存到words中，然后动态更新文本显示内容，实现打字机的效果
        this.isActive = true;
    }

    /// <summary>
    /// 执行打字任务
    /// </summary>
    private OnStartWriter(): void {
        if (this.isActive) {
            this.timer += Laya.timer.currTimer - this.latTime;
            this.latTime = Laya.timer.currTimer;
            if (this.timer >= this.charsPerSecond) {//判断计时器时间是否到达
                this.timer = 0;
                this.currentPos++;
                this.myText.text = this.words.slice(0, this.currentPos);//刷新文本显示内容

                if (this.currentPos >= this.words.length) {
                    this.EndType();
                }
            }
        }
    }

    /** 结束打字 直接显示*/
    public EndType(): void {
        this.isActive = false;
        this.timer = 0;
        this.currentPos = 0;
        this.myText.text = this.words;
    }

    /** 是否打字结束*/
    public IsTyping(): boolean {
        return this.isActive;
    }
}